from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
from urllib.request import quote, unquote
from time import sleep
import requests
from os import system,path

def download(url,file):
	res = requests.get(url)
	with open(file, 'wb') as f:
		f.write(res.content)
# Chrome浏览器
browser = webdriver.Chrome()
browser.set_window_size(500, 500)
browser.get(r"https://wiki.biligame.com/ys/index.php?title=%E8%A7%92%E8%89%B2")
characters = browser.find_elements(
	By.XPATH, '//div[@id="CardSelectTr"]//div/a[@class="image"]'
)
print("获取角色列表成功，共 " + str(len(characters)) + " 个角色")
charnameList = []
for character in characters:
	charname = unquote(character.get_attribute("href"), encoding="utf-8")
	charname = charname.replace("https://wiki.biligame.com/ys/文件:无背景-角色-", "")
	charname = charname.replace(".png", "")
	charnameList.append(charname)

print(charnameList)

print("=====准备下载=====")
system("mkdir 立绘")
system("mkdir 介绍立绘")
system("mkdir 祈愿")
system("mkdir 入队动作")

for charname in charnameList:
	charURL = "https://wiki.biligame.com/ys/" + charname
	print("========开始获取========")
	print("角色名：" + charname)
	print("角色介绍页URL：" + charURL)

	# 排除派蒙
	if charname == "派蒙":
		print("当前角色无立绘")
		continue

	# 判断文件是否存在
	filename = "./立绘/" + charname + " 立绘" + ".png"
	if not path.exists(filename):
		browser.get(quote("https://wiki.biligame.com/ys/文件:" + charname + "立绘.png", safe=";/?:@&=+$,", encoding="utf-8"))
		URL = browser.find_element(By.XPATH,'//*[@class="internal"]').get_attribute("href")
		download(URL,filename)
	else:
		print("文件已存在")

	filename = "./介绍立绘/" + charname + " 介绍立绘" + ".png"
	if not path.exists(filename):
		browser.get(quote("https://wiki.biligame.com/ys/文件:" + charname + "立绘2.png", safe=";/?:@&=+$,", encoding="utf-8"))
		URL = browser.find_element(By.XPATH,'//*[@class="internal"]').get_attribute("href")
		download(URL,filename)
	else:
		print("文件已存在")

	filename = "./祈愿/" + charname + " 祈愿" + ".png"
	if not path.exists(filename):
		browser.get(quote("https://wiki.biligame.com/ys/文件:" + charname + "抽卡立绘.png", safe=";/?:@&=+$,", encoding="utf-8"))
		URL = browser.find_element(By.XPATH,'//*[@class="internal"]').get_attribute("href")
		download(URL,filename)
	else:
		print("文件已存在")
	
	filename = "./入队动作/" + charname + " 入队动作" + ".gif"
	if not path.exists(filename):
		try:
			browser.get(quote("https://wiki.biligame.com/ys/文件:" + charname + "入队动作.gif", safe=";/?:@&=+$,", encoding="utf-8"))
			URL = browser.find_element(By.XPATH,'//*[@class="internal"]').get_attribute("href")
			download(URL,filename)
		except:
			print("无资源")
	else:
		print("文件已存在")